package com.onetech.adrewards.free.activities;



import java.util.List;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.adapters.ListSocialShareAdapter;
import com.onetech.adrewards.free.customviews.LoadMoreListView;
import com.onetech.adrewards.free.customviews.LoadMoreListView.OnLoadMoreListener;
import com.onetech.adrewards.free.dialogs.ShareFacebookDialog;
import com.onetech.adrewards.free.dialogs.ShareTwitterDialog;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.objects.SocialShareDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.onetech.adrewards.free.utils.PackageHelper;
import com.todddavies.components.progressbar.ProgressWheel;

public class SocialShareActivity extends BaseActivity implements
		OnLoadMoreListener, OnItemClickListener {
	private View mNotFoundData = null;
	private View mWaitingForLoading = null;
	private View mBtnRetry = null;
	private ProgressWheel mProgress = null;
	private LoadMoreListView mListView;
	// private View mNoPointHistoryView = null;
	// private TextView mTitleBar=null;

	private ListSocialShareAdapter mAdapter;
	private LoadPointHistory mLoadSocialShare = null;

	protected int pageNo = 1;
	
	private static String twitterShareText = "";

	//twitter
	public static SharedPreferences mSharedPref;
	private static final String SHARED_PREF = "android_twitter";
	private static final String USER_SCREEN_NAME = "tw_user_id";
	private static final String USER_NAME = "tw_user_name";
	private static final String USER_PIC = "tw_user_pic";
	public static final String PREF_KEY_SECRET = "oauth_token_secret";
	public static final String PREF_KEY_TOKEN = "oauth_token";
	
	
	
	public static Twitter mTwitter;	
	public static final String CONSUMER_KEY = "vrW3aRHhAfrDgH5G0XgiAAPuM";
	public static final String CONSUMER_SECRET = "2w9Byx0PRHtiEva3HYIaoQi2ttcdFuJmvf5GvaTtxw38qbH2lb";
	public static final String CALLBACK_URL = "twittercallback://socialshare";
	private static RequestToken requestToken;
	static final String IEXTRA_OAUTH_VERIFIER = "oauth_verifier";
	static final String IEXTRA_OAUTH_TOKEN = "oauth_token";
	
	//end twitter
	
	//Line Social
	private String mLineAppId = "jp.naver.line.android";
	private static final int LINE_INTENT_CODE = 0;
	public static final String LINE_PACKAGE_NAME = "jp.naver.line.android";
	public static final String LINE_CLASS_NAME = "jp.naver.line.android.activity.selectchat.SelectChatActivity";
	//End Line Social
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setMainView(R.layout.social_share_activity_layout);
		setAppTittle(getString(R.string.app_name));
		showFooterView(false);
		// showMyPoints(false);
		initView();
		initListener();
		
		ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
		configurationBuilder.setOAuthConsumerKey(CONSUMER_KEY);
		configurationBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
		Configuration configuration = configurationBuilder.build();
		mTwitter = new TwitterFactory(configuration).getInstance();
		
		
		
		mSharedPref	= getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
		
		Uri uri = getIntent().getData();
		if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
			String verifier = uri.getQueryParameter(IEXTRA_OAUTH_VERIFIER);
            try { 
                AccessToken accessToken = mTwitter.getOAuthAccessToken(requestToken, verifier); 
                Editor e = mSharedPref.edit();
                e.putString(PREF_KEY_TOKEN, accessToken.getToken()); 
                e.putString(PREF_KEY_SECRET, accessToken.getTokenSecret()); 
//                User user = mTwitter.verifyCredentials();
//                e.putString(USER_SCREEN_NAME, user.getScreenName());
//        		e.putString(USER_NAME, user.getName());
//        		e.putString(USER_PIC, user.getOriginalProfileImageURL());
                e.commit();
                
               
               
                
                
                ShareTwitterDialog mShareTwitterDialog=new ShareTwitterDialog(SocialShareActivity.this, "", twitterShareText);
        		mShareTwitterDialog.show();
        		
	        } catch (Exception e) { 
	               
	                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); 
			}
        }		
		
		
	}

	private void initView() {
		// mTitleBar=(TextView)findViewById(R.id.titleBar);
		// mTitleBar.setText(getString(R.string.point_history_view_title_bar)+
		// String.valueOf(mUserCoins)+"pt");

		mListView = (LoadMoreListView) findViewById(R.id.listSocial);
		mListView.setVisibility(View.GONE);
		mAdapter = new ListSocialShareAdapter(this);
		mListView.setAdapter(mAdapter);

		// mNoPointHistoryView = (LinearLayout)findViewById(R.id.no_history);
		// showNoHistory(false);
		initNotFoundAndLoadingView();
	}

	private void updateTitleBar() {
		// mTitleBar.setText(getString(R.string.point_history_view_title_bar)+
		// String.valueOf(mUserCoins)+"pt");
	}

	private void initListener() {
		mListView.setOnItemClickListener(this);
		initRetryButtonListener();
	}

	// private void showNoHistory(boolean isShowNoHistory) {
	// mNoPointHistoryView.setVisibility(isShowNoHistory ? View.VISIBLE
	// : View.GONE);
	// }

	protected void initNotFoundAndLoadingView() {
		mNotFoundData = (LinearLayout) findViewById(R.id.notFoundDataContainer);
		mWaitingForLoading = (LinearLayout) findViewById(R.id.waitingLoading);
		mProgress = (ProgressWheel) findViewById(R.id.progressWheel);
		mProgress.spin();
		showNotFoundOrLoadingView(false, true);
		mBtnRetry = (LinearLayout) findViewById(R.id.btnRetry);
	}

	protected void initRetryButtonListener() {
		mBtnRetry.setOnClickListener(this);
	}

	protected void showNotFoundOrLoadingView(boolean isShowNotFound,
			boolean isShowLoading) {
		if (isShowNotFound) {
			mNotFoundData.setVisibility(View.VISIBLE);
		} else {
			mNotFoundData.setVisibility(View.GONE);
		}
		if (isShowLoading) {
			mWaitingForLoading.setVisibility(View.VISIBLE);
		} else {
			mWaitingForLoading.setVisibility(View.GONE);
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnRetry:
			pageNo = 1;
			mListView.setVisibility(View.VISIBLE);
			showNotFoundOrLoadingView(false, true);
			loadSocialShare();
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		AdrewadsUtils.checkUId();
		getUserInfo();
		if (mAdapter != null && mAdapter.getCount() < 1) {
			loadSocialShare();
		}
		updateTitleBar();
	}

	private void loadSocialShare() {
		if (mLoadSocialShare == null
				|| mLoadSocialShare.getStatus() == Status.FINISHED) {
			mLoadSocialShare = new LoadPointHistory();
			mLoadSocialShare.execute();
		}
	}

//	private List<SocialShareDTO> createSocialData() {
//		
//		
//		List<SocialShareDTO> result = new ArrayList<SocialShareDTO>();
//		SocialShareDTO lineItem = new SocialShareDTO();
//		lineItem.id = "111";
//		lineItem.iconUrl = "";
//		lineItem.title = getString(R.string.line_title_social);
//		lineItem.description = getString(R.string.line_description_social);
//		lineItem.bonus = "1";
//
//		SocialShareDTO fbItem = new SocialShareDTO();
//		fbItem.id = "112";
//		fbItem.iconUrl = "";
//		fbItem.title = getString(R.string.fb_title_social);
//		fbItem.description = getString(R.string.fb_description_social);
//		fbItem.bonus = "1";
//
//		SocialShareDTO twitterItem = new SocialShareDTO();
//		twitterItem.id = "113";
//		twitterItem.iconUrl = "";
//		twitterItem.title = getString(R.string.twitter_title_social);
//		twitterItem.description = getString(R.string.twitter_description_social);
//		twitterItem.bonus = "1";
//
//		result.add(lineItem);
//		result.add(fbItem);
//		result.add(twitterItem);
//		return result;
//	}

	private class LoadPointHistory extends
			AsyncTask<Void, Void, List<SocialShareDTO>> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showNotFoundOrLoadingView(false, true);
			// showNoHistory(false);
		}

		@Override
		protected List<SocialShareDTO> doInBackground(Void... params) {
			try {
				return CommonModel.getInstance().getSocialShareBonus();
			} catch (Exception e) {
				return null;
			}
		}

		@Override
		protected void onPostExecute(List<SocialShareDTO> result) {
			super.onPostExecute(result);
			try {
				if (result != null) {
					if (result.size() < 1) {
						if (mAdapter.getCount() < 1) {
							showNotFoundOrLoadingView(false, false);
							// showNoHistory(true);
							mListView.setVisibility(View.GONE);
						} else {
							// showNoHistory(false);
							showNotFoundOrLoadingView(false, false);
							mListView.setVisibility(View.VISIBLE);
						}
					} else {
						if (pageNo == 1) {
							mAdapter.updateSocialList(result);
						} else {
							mAdapter.insertSocialList(result);
						}
						pageNo++;
						showNotFoundOrLoadingView(false, false);
						mListView.setVisibility(View.VISIBLE);
					}
				} else {
					if (mAdapter.getCount() < 1) {
						showNotFoundOrLoadingView(true, false);
						// showNoHistory(false);
						mListView.setVisibility(View.GONE);
					} else {
						// showNoHistory(false);
						showNotFoundOrLoadingView(false, false);
						mListView.setVisibility(View.VISIBLE);
					}
				}
			} catch (Exception e) {
			}
			mListView.onLoadMoreComplete();
		}
	}

	@Override
	public void onLoadMore() {
		loadSocialShare();
	}

	@Override
	public void onStart() {
		super.onStart();
		// The rest of your onStart() code.
		try {
			EasyTracker.getInstance(this).activityStart(this); // Add this
																// method.
		} catch (Exception e) {
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		// The rest of your onStop() code.
		try {
			EasyTracker.getInstance(this).activityStop(this); // Add this
																// method.
		} catch (Exception e) {
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
		SocialShareDTO item=mAdapter.getItem(position);
		if(item!=null){
			if(item.type.equals("6")){ //Line cointype=6
				shareLineTextSocail(item.shareText);
				return;
			}
			if(item.type.equals("7")){ //fb cointype=7
				Intent shareFBDialog=new Intent(getApplicationContext(), ShareFacebookDialog.class);
				shareFBDialog.putExtra(Intent.EXTRA_TEXT, item.shareText);
				startActivity(shareFBDialog);
				return;
			}
			if(item.type.equals("8")){ //Twitter cointype=8
				twitterShareText = item.shareText;
				LoginTwitter();
			}
		}
	}
	
	
	/**
	 * check if the account is authorized
	 * @return
	 */
	private boolean isConnected() {
		return mSharedPref.getString(PREF_KEY_TOKEN, null) != null;
	}
	
	private void LoginTwitter(){
		
		
		if (isConnected()) {			
			showTwitterDialog();
		} else {
			signinTwitter();
		}		
	}

	private void showTwitterDialog() {
		ShareTwitterDialog mShareTwitterDialog=new ShareTwitterDialog(SocialShareActivity.this, "", twitterShareText);
		mShareTwitterDialog.show();
	}
	private void signinTwitter() {
		
		try {
			requestToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
			Toast.makeText(this, getString(R.string.twitter_please_login), Toast.LENGTH_LONG).show();
			this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
		} catch (TwitterException e) {
			showToast(e.getErrorMessage());
		}
		
	}
	
//	private void getCredentials() {
//		final ProgressDialog progressDlg = new ProgressDialog(this);
//		
//		progressDlg.setMessage("Getting credentials...");
//		progressDlg.setCancelable(false);
//		progressDlg.show();
//		TwitterRequest request = new TwitterRequest(mTwitter.getConsumer(), mTwitter.getAccessToken());
//		request.verifyCredentials(new TwitterRequest.VerifyCredentialListener() {
//			
//			@Override
//			public void onSuccess(TwitterUser user) {
//				progressDlg.dismiss();
//				//showToast("Hello " + user.name);
//				saveCredential(user.screenName, user.name, user.profileImageUrl);
//				showTwitterDialog();
//			}
//			
//			@Override
//			public void onError(String error) {
//				progressDlg.dismiss();
//				showToast(error);
//			}
//		});
//	}
	
	
//	public void saveCredential(String screenName, String name, String profilePic) {
//		Editor editor = mSharedPref.edit();
//		editor.putString(USER_SCREEN_NAME, screenName);
//		editor.putString(USER_NAME, name);
//		editor.putString(USER_PIC, profilePic);
//		editor.commit();
//	}
//	
//	public void clearCredential() {
//		mTwitter.clearSession();
//		Editor editor = mSharedPref.edit();
//		editor.putString(USER_SCREEN_NAME, "");
//		editor.putString(USER_NAME, "");
//		editor.putString(USER_PIC, "");
//		editor.commit();
//	}
	
//	public String getScreenName() {
//		return mSharedPref.getString(USER_SCREEN_NAME, "");
//	}
//	
//	public String getUserName() {
//		return mSharedPref.getString(USER_NAME, "");
//	}
//	
//	public String getProfilePicture() {
//		return mSharedPref.getString(USER_PIC, "");
//	}
	
	
	public void showToast(String text) {
		Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
	}
	

	
	
	private void shareLineTextSocail(String text){
		String TAG = "[LineKitANE] ShareText -";
		if(PackageHelper.getInstance(getApplicationContext()).isInstalled(mLineAppId)){
			
			
	        try {
	        	
	        	CommonModel.getInstance().doSocialCoin("6");
	        	
	        	Intent intent = new Intent(Intent.ACTION_SEND);
	        	intent.setClassName(LINE_PACKAGE_NAME, LINE_CLASS_NAME);
	        	intent.setType("text/plain");
	        	intent.putExtra(Intent.EXTRA_TEXT, text);
	        	startActivity(intent);
//				String uri = "line://msg/text/" + text;
//				Intent intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME);
//				intent.setType("text/plain");
//				startActivity(intent);
			} catch (Exception e) {  
				Log.e(TAG, e.toString());
			} 
		}else{
			showToast(getString(R.string.line_social_not_installed_message));
		}
	}

	

	public void updateUser() {
		getUserInfo();
		
	}
	
	
	
}
